package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间的营业额
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //组装dateList
        ArrayList<LocalDate> list = getLocalDates(begin, end);
        //计算和封装营业数据数据
        ArrayList<Double> turnoverList = new ArrayList<>();
        for (LocalDate time : list) {
            //将类型封装成LocalDateTime
            LocalDateTime beginTime = LocalDateTime.of(time, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(time, LocalTime.MAX);
            //封装成map作参数
            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            //传给mapper处理并存储结果
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(list, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 统计指定时间的用户数量
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //组装dateList
        ArrayList<LocalDate> list = getLocalDates(begin, end);

        ArrayList<Integer> totalUserList = new ArrayList<>();
        ArrayList<Integer> newUserList = new ArrayList<>();
        for (LocalDate time : list) {
            //将类型封装成LocalDateTime
            LocalDateTime beginTime = LocalDateTime.of(time, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(time, LocalTime.MAX);

            //封装成map作参数
            Map map = new HashMap<>();
            map.put("end", endTime);

            //统计每天用户总量
            Integer total_count = userMapper.getByMap(map);

            map.put("begin", beginTime);
            //统计每天新增用户数量
            Integer new_count = userMapper.getByMap(map);

            totalUserList.add(total_count);
            newUserList.add(new_count);
        }


        return UserReportVO.builder()
                .dateList(StringUtils.join(list, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 订单统计
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> list = getLocalDates(begin, end);
        //每天订单数
        ArrayList<Integer> orderCountList = new ArrayList<>();
        //每天有效订单数
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate time : list) {
            //将类型封装成LocalDateTime
            LocalDateTime beginTime = LocalDateTime.of(time, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(time, LocalTime.MAX);

            //统计每天订单数
            Integer count = getCount(beginTime,endTime,null);

            //查有效订单
            Integer validCount =getCount(beginTime,endTime,Orders.COMPLETED);

            orderCountList.add(count);
            validOrderCountList.add(validCount);
        }
        //订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //计算完成率
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0){
            orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount;

        }
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .dateList(StringUtils.join(list, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .build();
        return orderReportVO;
    }


    //将横坐标的数据返回
    private static ArrayList<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        //组装dateList
        ArrayList<LocalDate> list = new ArrayList<>();
        list.add(begin);
        while (!begin.equals(end)) {
            //加一天
            begin = begin.plusDays(1);
            list.add(begin);
        }
        return list;
    }
    //将动态查询数据
    public Integer getCount(LocalDateTime beginTime,LocalDateTime endTime,Integer status){
        //封装成map作参数
        Map map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", status);
        Integer count = orderMapper.getOrderCount(map);
        return count;
    }
    /**
     * 查询销量排名top10接口
     */
    @Override
    public SalesTop10ReportVO getTop10Statistics(LocalDate begin, LocalDate end) {
        //将类型封装成LocalDateTime
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> top10Sales = orderMapper.getTop10Sales(beginTime, endTime);
        //封装name集合
        List<String> name = top10Sales.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(name, ",");
        //封装number集合
        List<Integer> number = top10Sales.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(number, ",");
        System.out.println(nameList+":"+numberList);
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }
    /**
     * 导出运营数据报表
     */
    @Override
    public void exportBusinessDate(HttpServletResponse response) {
        //查询数据库，查找运营数据
        LocalDate beginDay = LocalDate.now().minusDays(30);
        LocalDate endDay = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDay, LocalTime.MIN), LocalDateTime.of(endDay, LocalTime.MAX));
        //通过POI写入excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //创建新的excle文件
            XSSFWorkbook sheets = new XSSFWorkbook(in);
            //获取sheet页
            XSSFSheet sheet = sheets.getSheet("Sheet1");
            //获取行中单元格并设置值 时间值
             sheet.getRow(1).getCell(1).setCellValue("时间："+beginDay+"至"+endDay);
            //营业额设置 第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            //订单完成率
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //新增用户数
            row.getCell(6).setCellValue(businessData.getNewUsers());
            // 第五行
            row = sheet.getRow(4);
            //有效订单
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            //平均客单价
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate beginTime = beginDay.plusDays(i);
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(beginTime, LocalTime.MIN), LocalDateTime.of(beginTime, LocalTime.MAX));

                //获取第七行
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(beginDay.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
            }
            //通过输出流下载文件到客户端
            ServletOutputStream out = response.getOutputStream();
            sheets.write(out);

            //关闭资源
            out.close();
            sheets.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
